import store from '../../store';
import request from '../request.js';
import { encrypt } from './rsa.js';
import cryptoJs from 'crypto-js';


// 接口授权
export const apiAuthorization = (headers, param) => {
  const user = store.getState()?.user?.user;
  const token = user?.token;
  const userId = user?.userId;
  if (userId == undefined || userId == null || userId == 0 || token == undefined || token == null || token == '') {
    return headers;
  }

  const time = new Date();
  const timestamp = time.valueOf().toString();
  const minNum = 10000;
  const maxNum = 100;
  const nonce = parseInt(Math.random() * (maxNum - minNum + 1) + minNum, 10).toString();
  const conditions = typeof param === 'string' ? param.toString() : JSON.stringify(param);
  const signature = (userId.toString() + timestamp + nonce + token + conditions).toLowerCase();
  console.log(signature);
  headers['userid'] = userId;
  headers['timestamp'] = time.valueOf();
  headers['nonce'] = nonce;
  headers['signature'] = cryptoJs.MD5(signature).toString();
  return headers;
}

// api 通道数据签名
export const apiChannelAuthorization = async (headers, param) => {

  const getChannel = () => {
    return request({
      url: `/api/channel`,
      method: 'GET',
    })
  }
  return getChannel().then(res => {
    if (res.status == 200) {
      headers['channel'] = res.data.result.channel;
      headers['Content-Type'] = 'text/plan';
      console.log(headers);
      if (typeof param === 'string')
        return encrypt(param, res.data.result.key);
      return encrypt(JSON.stringify(param), res.data.result.key);
    }
    return '';
  }).catch(err => {
    console.log(err)
  });
}
